package cn.com.common.job.task;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.constants.GasConstants;
import cn.com.gas.entity.GasStationDeptEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasStationDeptService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.system.entity.SysParameterEntity;
import cn.com.system.service.SysParameterService;
import cn.com.thirdparty.entity.ProvinceGasCamQualityEntity;
import cn.com.thirdparty.mapper.ProvinceGasCamQualityMapper;
import cn.com.util.HmacSha256Utils;
import cn.com.util.MD5Utils;
import cn.com.util.RestTemplateUtil;
import cn.com.util.TsBqUtils;

/**
 * 定时任务(演示Demo，可删除) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Component("gasStationInfoUpdateProcessTask")
@DisallowConcurrentExecution
public class GasStationInfoUpdateProcessTask {
	
	@Value("${gasstation.timedTask.gasStationInfoUpdateProcessTask}")
	private String gasStationInfoUpdateProcessTask;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasStationDeptService gasStationDeptService;
	/*@Autowired
	private GasServerAreaService gasServerAreaService;*/
	@Autowired
	private ProvinceGasCamQualityMapper provinceGasCamQualityMapper;
	@Autowired
	private SysParameterService sysParameterService;
	
	
	
	@Value("${gasstation.videosQueryVideoGetGroupsOfflineUrl}")
	private String url;

	@Value("${gasstation.thirdPartyPass}")
	private String pass;
	@Value("${gasstation.thirdPartyUser}")
	private String user;
	
	public void run(String params) throws Exception {
		logger.debug("gasStationInfoUpdateProcessTask定时任务正在执行，参数为：{}", params);
		
		logger.debug("application参数为gasStationInfoUpdateProcessTask：{}", gasStationInfoUpdateProcessTask);

		if (gasStationInfoUpdateProcessTask.equals(Constants.JOB_STOP)) {

			logger.debug("application配置文件控制不执行gasStationInfoUpdateProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasStationInfoUpdateProcessTask定时任务");
		
		}
		
		// String url =
		// "http://21.0.0.60:5000/Videos/QueryVideo/GetGroupsOffline";

		// 区域
		List<GasStationDeptEntity> list = gasStationDeptService.list();

		for (GasStationDeptEntity gasStationDeptEntity : list) {
			String endangerId = gasStationDeptEntity.getEndangerId();
			String deptId = gasStationDeptEntity.getDeptId();
			
			Map<String, Object> map = new HashMap<>();

			map.put("api", user);
			map.put("isMobile", "1");
			map.put("offline", "0");
			map.put("parentId", endangerId);
			map.put("parentType", "group");
			map.put("sign", sign(url, map));
			String domainResponse = removeFirstAndLastChar(RestTemplateUtil.get(url, map));

			if (TsBqUtils.isNotNull(domainResponse)) {
				JSONArray domainJsonArray = JSONArray.parseArray(domainResponse);
				List<GasStationinfoEntity> listDomain = JSONArray.parseArray(JSON.toJSONString(domainJsonArray),
						GasStationinfoEntity.class);

				if (TsBqUtils.isNotNull(listDomain)) {

					for (GasStationinfoEntity domain : listDomain) {
						saveOrUpdateGasStationinfo(domain,deptId);
						String type = domain.getType();
						if (type.equals("group") || type.equals("domain")) {
							requertRecursion(domain,deptId);
						}
					}
				}
			}
		}

	}

	private void saveOrUpdateGasStationinfo(GasStationinfoEntity gasStationinfo,String deptId) {
		Date date = new Date();
		// 创建一个SimpleDateFormat对象，定义日期格式
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 将Date对象转换为指定格式的字符串

		String id = gasStationinfo.getId();
		GasStationinfoEntity gasStationinfoEntity = gasStationinfoService.getById(id);

		if (TsBqUtils.isNotNull(gasStationinfoEntity)) {
			
			String type = gasStationinfo.getType();
			
			String name = gasStationinfo.getName();
			String online = gasStationinfo.getOnline();
			
			// 更新数据  更新摄像头名称
			if("cam".equals(type)){
				
			}else{
				gasStationinfo.setName(gasStationinfoEntity.getName());
			}
			
			gasStationinfo.setAddress(gasStationinfoEntity.getAddress());
			gasStationinfo.setTaxorgcode(gasStationinfoEntity.getTaxorgcode());
			gasStationinfo.setIsAnalyse(gasStationinfoEntity.getIsAnalyse());

			gasStationinfo.setGasLocation(gasStationinfoEntity.getGasLocation());
			gasStationinfo.setGasCoverage(gasStationinfoEntity.getGasCoverage());
			
			gasStationinfo.setTaxpayerName(gasStationinfoEntity.getTaxpayerName());
			gasStationinfo.setTaxpayerCode(gasStationinfoEntity.getTaxpayerCode());
			gasStationinfo.setGastype(gasStationinfoEntity.getGastype());
			gasStationinfo.setGasoline(gasStationinfoEntity.getGasoline());
			gasStationinfo.setGasolineMoto(gasStationinfoEntity.getGasolineMoto());
			gasStationinfo.setGasolineFarming(gasStationinfoEntity.getGasolineFarming());
			gasStationinfo.setGasolineLighttruck(gasStationinfoEntity.getGasolineLighttruck());
			gasStationinfo.setDiesel(gasStationinfoEntity.getDiesel());
			gasStationinfo.setThirdPartyId(gasStationinfoEntity.getThirdPartyId());
			
			if(type.equals("group")){
				gasStationinfo.setOnline(TsBqUtils.isOnline(name, online));
			}
			

			gasStationinfo.setUpdateTime(date);
			gasStationinfo.setUpdateId("sysjob");

			// 判断摄像头是否在线
			// String isAnalyse = gasStationinfo.getIsAnalyse();
			// LambdaQueryWrapper<GasServerAreaEntity> queryServerArea = Wrappers.lambdaQuery();
			// queryServerArea.eq(GasServerAreaEntity::getCamid, id);

			// 更新摄像头taxorgcode 更父亲ID 保持一致
			if ("cam".equals(type)) {
				String pid = gasStationinfo.getPid();
				GasStationinfoEntity stationinfo = gasStationinfoService.getById(pid);
				String taxorgcode = stationinfo.getTaxorgcode();
				gasStationinfo.setTaxorgcode(taxorgcode);
			}

		} else {
			// 新增数据
			gasStationinfo.setTaxorgcode(deptId);
			gasStationinfo.setCreateTime(date);
			gasStationinfo.setCreateId("sysjob");

		}

		gasStationinfo.setDeleted(Constants.DELETEED_NOT);

		gasStationinfoService.saveOrUpdate(gasStationinfo);
		
		// 更新 省平台
		try {
			SysParameterEntity parameterEntity106 = sysParameterService.getById("parameter106");

			if (TsBqUtils.isNotNull(parameterEntity106)) {
				String parameter106 = parameterEntity106.getParameter();
				if ("Y".equals(parameter106)) {
					if ("cam".equals(gasStationinfo.getType())&&"1".equals(gasStationinfo.getIsanalyser())) {
						String camid = gasStationinfo.getId();
						LambdaQueryWrapper<ProvinceGasCamQualityEntity> provinceQueryWrapper = Wrappers.lambdaQuery();
						provinceQueryWrapper.eq(ProvinceGasCamQualityEntity::getCamId, camid);
						List<ProvinceGasCamQualityEntity> listProvinceGasCamQuality = provinceGasCamQualityMapper.selectList(provinceQueryWrapper);
						String iconSkin = gasStationinfo.getIconSkin();
						String stateStr = "";
						if(TsBqUtils.isNotNull(listProvinceGasCamQuality)){
							ProvinceGasCamQualityEntity provinceGasCamQualityEntity = listProvinceGasCamQuality.get(0);
							provinceGasCamQualityEntity.setUpdateTime(date);
							
							if(GasConstants.ICON_SKIN_ON.equals(iconSkin)){
								// 在线
								stateStr = "在线";
								provinceGasCamQualityEntity.setCamOnlineState("1");
							}else{
								// 离线
								stateStr = "离线";
								provinceGasCamQualityEntity.setCamOnlineState("0");
							}
							logger.info("更新GasCamQuality表camOnlineState摄像头:"+camid+",状态："+stateStr);
							provinceGasCamQualityMapper.updateById(provinceGasCamQualityEntity);
							
						}else{
							// 新增
							ProvinceGasCamQualityEntity provinceGasCamQualityEntity = new ProvinceGasCamQualityEntity();
							provinceGasCamQualityEntity.setCamId(camid);
							provinceGasCamQualityEntity.setStationinfoId(gasStationinfo.getPid());
							
							if(GasConstants.ICON_SKIN_ON.equals(iconSkin)){
								// 在线
								stateStr = "在线";
								provinceGasCamQualityEntity.setCamOnlineState("1");
							}else{
								// 离线
								stateStr = "离线";
								provinceGasCamQualityEntity.setCamOnlineState("0");
							}
							provinceGasCamQualityEntity.setDeleted(Constants.DATA_NOT_DELETED);
							provinceGasCamQualityEntity.setCreateTime(date);
							
							logger.info("新增GasCamQuality表camOnlineState摄像头:"+camid+",状态："+stateStr);
							provinceGasCamQualityMapper.insert(provinceGasCamQualityEntity);
							
						}
						
					}
				}
			}
		} catch (Exception e) {
			logger.error("写入GasCamQuality表camOnlineState异常:" + e.getMessage());

		}
		
		
	}

	// 写入

	private void requertRecursion(GasStationinfoEntity gasStationinfo,String deptId) throws UnsupportedEncodingException {

		Map<String, Object> map = new HashMap<>();
		map.put("api", user);
		map.put("isMobile", "1");
		map.put("offline", "0");
		map.put("parentId", gasStationinfo.getId());
		map.put("parentType", gasStationinfo.getType());
		map.put("sign", sign(url, map));
		String response = removeFirstAndLastChar(RestTemplateUtil.get(url, map));

		if (TsBqUtils.isNotNull(response)) {
			try {
				JSONArray jsonArray = JSONArray.parseArray(response);
				List<GasStationinfoEntity> list = JSONArray.parseArray(JSON.toJSONString(jsonArray),
						GasStationinfoEntity.class);
	
				if (TsBqUtils.isNotNull(list)) {
					for (GasStationinfoEntity gasStationinfoEntity : list) {
	
						saveOrUpdateGasStationinfo(gasStationinfoEntity,deptId);
						String type = gasStationinfoEntity.getType();
						if (type.equals("group") || type.equals("domain")) {
							requertRecursion(gasStationinfoEntity,deptId);
						}
	
					}
				}
			} catch (Exception e) {
				logger.debug("gasStationInfoProcessTask定时任务正在执行，异常：{}", e.getMessage());

			}
		}
	}

	private String sign(String url, Map<String, Object> parameter) throws UnsupportedEncodingException {
		if (!parameter.isEmpty()) {
			url = url + "?";
			for (String key : parameter.keySet()) {
				url = url + key + "=" + parameter.get(key) + "&";
			}
			url = url.substring(0, url.length() - 1);
		}

		String encrypt = MD5Utils.encrypt(pass);
		byte[] hmacSHA256 = HmacSha256Utils.hmacSHA256(url, encrypt);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
		String encodedString = URLEncoder.encode(new String(encodedBytes), "UTF-8");

		return encodedString;
	}

	public String removeFirstAndLastChar(String s) {
		if (s.length() <= 2) {
			return ""; // 如果字符串长度小于等于2，则返回空字符串
		}
		String str = s.substring(1, s.length() - 1);
		String replaceAll = str.replaceAll("\\\\", "");
		return replaceAll;

	}
}
